//
//  RelatedQustionsViewController.m
//  安好
//
//  Created by lianchuang on 14/12/4.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "RelatedQustionsViewController.h"
#import "RelatedQuestionViewCell.h"
#import "RelationAnswerViewCell.h"
#import "AnswerView.h"
@interface RelatedQustionsViewController ()

@end

@implementation RelatedQustionsViewController
- (void)viewWillDisappear:(BOOL)animated
{
    [self hiddenActionView];
    [self hiddenLabel];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    UIBarButtonItem *backImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backClicked)];
    backImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backImg;
    self.navigationItem.title=@"相关问题";
    self.tableview.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight-64);
    self.tableview.dataSource=self;
    self.tableview.delegate=self;
    self.tableview.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.tableview addFooterWithTarget:self action:@selector(loadQuestionMessgae)];
    self.answerArrays=[[NSMutableArray alloc]init];
    [self loadQuestionMessgae];
}
- (void)loadQuestionMessgae
{
    [self showActionView];
    self.page=self.page+1;
    NSString * requestURL = [NSString stringWithFormat:@"%@question/cndetail/",kBaseURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"platform": kPlatform,
                                 @"version":kVersion,
                                 @"page":[NSString stringWithFormat:@"%ld",self.page],
                                 @"qid":self.qid,
                                 };
    [manager POST:requestURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.tableview footerEndRefreshing];

        [self hiddenActionView];
        NSString *status=[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"status"]];
        if ([status isEqualToString:@"1"]) {

            if ([[responseObject valueForKey:@"data"] count]==0) {
                [self.tableview footerEndRefreshing];
            }else
            {
                for (int i=0; i<[[responseObject valueForKey:@"data"] count]; i++) {
                    [self.answerArrays addObject:[[responseObject valueForKey:@"data"] objectAtIndex:i]];
                }
            }
            [self.tableview reloadData];
        }else
        {
//            [self shouLabel:@"暂无数据"];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        [self.tableview footerEndRefreshing];
//        [self shouLabel:@"暂无数据"];
    }];
}
#pragma  mark --------UITableviewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return 1;
    }else
        return self.answerArrays.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        static NSString *indentifier=@"Questioncell";
        RelatedQuestionViewCell *questionViewCell=[tableView dequeueReusableCellWithIdentifier:indentifier];
        if (!questionViewCell) {
            if (kScreenWidth==414) {
                questionViewCell=[[[NSBundle mainBundle]loadNibNamed:@"RelatedQuestionViewCell" owner:self options:nil] lastObject];
            }
            else{
                questionViewCell=[[[NSBundle mainBundle]loadNibNamed:@"RelatedQuestionViewCell" owner:self options:nil] firstObject];
            }
        }
        if (self.questionInfo) {
            if ([[NSString stringWithFormat:@"%@",[self.questionInfo valueForKey:@"sex"]] isEqualToString:@"1"]) {
                questionViewCell.sex.text=@"男";
            }else
            {
                questionViewCell.sex.text=@"女";
            }
            questionViewCell.age.text=[NSString stringWithFormat:@"%@岁",[self.questionInfo valueForKey:@"age"]];
            questionViewCell.dateline.text=[self.questionInfo valueForKey:@"dateline"];
            [self autosizeFontAndSize:questionViewCell.dateline withText:questionViewCell.dateline.text];
            
            questionViewCell.dateline.frame=CGRectMake(questionViewCell.dateline.right-questionViewCell.dateline.width, questionViewCell.dateline.top, questionViewCell.dateline.width, questionViewCell.dateline.height);
            
            questionViewCell.clock.frame=CGRectMake(questionViewCell.dateline.left-5-12, questionViewCell.dateline.top, questionViewCell.clock.width, questionViewCell.clock.height);
            questionViewCell.partline.frame=CGRectMake(kScreenWidth==414?20:15, kScreenWidth==414?56: 44, 290, 0.5);
            
            
            
            questionViewCell.content.text=[[self.questionInfo valueForKey:@"content"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet ]];
//            [self autosizeFontAndSize:questionViewCell.content withText:questionViewCell.content.text];
            
            CGSize autosize=[self autosizeFontAndSize:questionViewCell.content withText:questionViewCell.content.text withWidth:kScreenWidth-40];
            questionViewCell.content.frame=CGRectMake(questionViewCell.content.left, questionViewCell.content.top, 280,autosize.height);
            
            questionViewCell.bottom.frame=CGRectMake(0,questionViewCell.content.bottom+15 , kScreenWidth, 0.5);
        }
        
        
        questionViewCell.selectionStyle=UITableViewCellSelectionStyleNone;
        return questionViewCell;
    }else
    {
        static NSString *indentifer=@"AnswerViewCell";
        RelationAnswerViewCell *answerViewCell=[tableView dequeueReusableCellWithIdentifier:indentifer];
        if (!answerViewCell) {
            if (kScreenWidth==414) {
                answerViewCell=[[[NSBundle mainBundle]loadNibNamed:@"RelationAnswerViewCell" owner:self options:nil] lastObject];
            }else if(kScreenWidth==320){
                answerViewCell=[[[NSBundle mainBundle]loadNibNamed:@"RelationAnswerViewCell" owner:self options:nil] firstObject];
            }else
            {
                answerViewCell=[[[NSBundle mainBundle]loadNibNamed:@"RelationAnswerViewCell" owner:self options:nil] objectAtIndex:1];

            }
        }
        if (self.answerArrays.count>0) {
            NSDictionary *dic=[self.answerArrays objectAtIndex:indexPath.row];
            answerViewCell.docName.text =  [dic valueForKey:@"doctorname"];
            [answerViewCell.HeadImage setImageWithURL:[NSURL URLWithString:[dic valueForKey:@"avatar"]] placeholderImage:[UIImage imageNamed:@"默认头像"]];
            answerViewCell.HeadImage.layer.cornerRadius=3;
            answerViewCell.HeadImage.layer.masksToBounds=YES;
            answerViewCell.docGoodat.text=[[dic valueForKey:@"expertise"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            
            [self autosizeFontAndSize:answerViewCell.docGoodat withText:answerViewCell.docGoodat.text];
            
            answerViewCell.content.text=[[dic valueForKey:@"acontent"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet ]];
            [self autosizeFontAndSize:answerViewCell.content withText:answerViewCell.content.text];
            answerViewCell.content.frame=CGRectMake(answerViewCell.content.left, answerViewCell.docGoodat.bottom+20,answerViewCell.content.width ,answerViewCell.content.height);
            answerViewCell.contentBack.frame=CGRectMake(answerViewCell.contentBack.left, answerViewCell.content.top-18,answerViewCell.content.width+30 , answerViewCell.content.height+25);
            answerViewCell.contentBack.image=[[UIImage imageNamed:@"related_flag.png"] stretchableImageWithLeftCapWidth:40 topCapHeight:15];
        }
        answerViewCell.selectionStyle=UITableViewCellSelectionStyleNone;

        return answerViewCell;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section==1) {
        AnswerView *view;
        if (kScreenWidth==414) {
            view=[[[NSBundle mainBundle]loadNibNamed:@"AnswerView" owner:self options:nil] lastObject ];
        }else{
            view=[[[NSBundle mainBundle]loadNibNamed:@"AnswerView" owner:self options:nil] firstObject ];
        }
        view.answerCount.text=[NSString stringWithFormat:@"共%ld条医生回复",self.answerArrays.count];
        return view;
    }else return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==1) {
        return 54;
    }else
        return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        RelatedQuestionViewCell *cell=(RelatedQuestionViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
        
        return cell.content.bottom+15;
    }else{
        RelationAnswerViewCell *answerViewCell=(RelationAnswerViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
        return answerViewCell.contentBack.bottom+15;
    }
}
/**
 *  只适应
 *  @param label 传入label、
 *  @param text  传入label.text
 */
- (void)autosizeFontAndSize:(UILabel *)label withText:(NSString *)text
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:5];//调整行间距
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [text length])];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    label.attributedText = attributedString;
    [label sizeToFit];
}
- (CGSize)autosizeFontAndSize:(UILabel *)label withText:(NSString *)text withWidth:(float)width
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:5];//调整行间距
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [text length])];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    label.attributedText = attributedString;
    //    [label sizeToFit];
    CGSize size=[label sizeThatFits:CGSizeMake(width, MAXFLOAT)];
    return size;
}
//- (CGSize)autolayoutText:(NSString *)text WithTextLabel:(UILabel *)textlabel WithWidth:(CGFloat )width
//{
//    
//    CGSize size =CGSizeMake(width,0);
//    textlabel.lineBreakMode=NSLineBreakByCharWrapping;
//    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:textlabel.font,NSFontAttributeName,nil];
//    CGSize  actualsize;
//    actualsize =[textlabel.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine  attributes:tdic context:nil].size;
//    return actualsize;
//}

- (void)backClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
